package com.zhuhjay.common.redis.config;

import cn.hutool.core.util.StrUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ZhuHJay
 * @date 2023/10/12 9:15
 */
@Configuration
public class CacheConfig {

    /**
     * RedissonClient
     * 创建的锁都放置在普通的redis数据库的下一个数据库中, 防止和缓存的数据混淆
     */
    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        int poolSize = redisProperties.getJedis().getPool().getMaxIdle() / 2;
        int idleSize = redisProperties.getJedis().getPool().getMinIdle() / 2;
        config.useSingleServer()
                // 设置数据库为普通数据库的下一个数据库
                .setDatabase((redisProperties.getDatabase() + 1) % 16)
                // 兼容无密码
                .setPassword(StrUtil.isBlank(redisProperties.getPassword()) ? null : redisProperties.getPassword())
                .setAddress(StrUtil.format("redis://{}:{}", redisProperties.getHost(), redisProperties.getPort()))
                .setConnectionPoolSize(poolSize > 0 ? poolSize : 5)
                .setConnectionMinimumIdleSize(idleSize > 0 ? idleSize : 1);
        return Redisson.create(config);
    }

}
